package ApplicationLogic.modelMiscTools;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;


import businessLogic.model.AbstractModel;

public class ChildModelInsertor implements IChildModelInsertor
{

	@Override
	public void InsertNonPrimitiveAttributeIntoParent(AbstractModel parent,
			String parentColumnName, AbstractModel child) throws Exception
	{
		Field parentChildReferenceField = parent.getClass().getDeclaredField(parentColumnName);	
		parentChildReferenceField.setAccessible(true);
		Class FieldClass = parentChildReferenceField.getType();
		
		
		if(FieldClass.isArray())
		{
			//Class FieldClass = parentChildReferenceField.getDeclaringClass();
			System.out.println("Is a common array");
			throw new Exception();
			
		}
		else if (Collection.class.isAssignableFrom(FieldClass)) //if its a Collection (ArrayList, etc)
		{
			System.out.println("Is a collection");
			Collection c = (Collection)parentChildReferenceField.get(parent);
			c.add(child); //add the child to the collection
			parentChildReferenceField.set(parent, c); //and set the collection to the parent instance
		}
		else //otherwise is not a collection, or array, so a plain object
		{
			System.out.println("Is a plain model");
			parentChildReferenceField.set(parent,child);
		}
		
	}
	


}
